package com.writing.aspect;

import com.writing.annotation.RequireAdmin;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 角色权限切面
 * 用于检查用户是否具有管理员权限
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class RoleAspect {
    
    @Before("@annotation(requireAdmin)")
    public void checkAdminRole(JoinPoint joinPoint, RequireAdmin requireAdmin) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            throw new RuntimeException("无法获取请求信息");
        }
        
        String role = (String) request.getAttribute("role");
        log.debug("检查权限，用户角色: {}", role);
        
        if (role == null || !"ADMIN".equals(role)) {
            throw new RuntimeException(requireAdmin.message());
        }
    }
    
    /**
     * 获取当前请求
     */
    private HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        }
        return null;
    }
}

